Thumb

What is foreach loop?

1/8/2020 5:40:43 AM

Foreach loop is another loop which work each item from the collection. Foreach loop is very important in C#. This loop work in generic or non-generic collection. This loop has two part one is collection and another is each item variable to take the value. Now given bellow the foreach loop example code and explain the code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using testForClass1;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace testFor
{
    public class Program
    {
        static void Main(string[] args)
        {
            String[] Days = new string[7] { "Sun", "Mon", "Tue", "Wed","Thu","Fri","Sa" };
            List<string> Names = new List<string>() { "Jesy","Reza","Tofile","Sid" };
            foreach (var day in Days)
            {
                Console.WriteLine(day);
            }
            Console.WriteLine();
            foreach (var name in Names)
            {
                Console.WriteLine(name);
            }
            Console.Read();
        }
    }
}

In this code we write Days string array and also write list of string name as Names. Now print the value by the foreach loop.